import pyautogui
import time
from tkinter import messagebox, Tk, filedialog

# 配置参数
WINDOW_WAIT_TIME = 3  # 缩短等待时间
MAX_ATTEMPTS = 10

class SimpleAutoSaver:
    def __init__(self):
        self.target_folder = self.get_target_folder()
        self.processed_count = 0

    @staticmethod
    def get_target_folder():
        """通过对话框获取保存路径"""
        root = Tk()
        root.withdraw()
        folder = filedialog.askdirectory(title="请选择保存文件夹")
        root.destroy()
        return folder or "."

    def set_save_path(self):
        """快速设置保存路径"""
        try:
            pyautogui.hotkey("alt", "d")
            time.sleep(0.2)
            pyautogui.write(f'"{self.target_folder}"')  # 自动处理路径空格
            pyautogui.press("enter")
            time.sleep(0.3)
        except Exception as e:
            messagebox.showerror("错误", f"路径设置失败: {str(e)}")
            raise

    def save_current_file(self):
        """执行单个文件保存流程"""
        pyautogui.hotkey("ctrl", "s")
        time.sleep(0.5)
        self.set_save_path()
        pyautogui.press("enter")  # 确认保存
        time.sleep(0.5)
        pyautogui.press("enter")  # 处理覆盖提示
        self.processed_count += 1

    def main_process(self):
        """主控制流程"""
        messagebox.showinfo("提示", f"请切换到图片查看窗口后点击确定")
        
        for _ in range(MAX_ATTEMPTS):
            try:
                self.save_current_file()
                pyautogui.press("right")  # 切换到下一张
                time.sleep(0.5)
            except Exception as e:
                messagebox.showerror("错误", f"操作中断: {str(e)}")
                break

        messagebox.showinfo("完成", f"成功保存 {self.processed_count} 个文件")

if __name__ == "__main__":
    try:
        saver = SimpleAutoSaver()
        saver.main_process()
    except Exception as e:
        messagebox.showerror("错误", f"程序异常: {str(e)}")
